import uuid

from rest_framework.views import APIView
from rest_framework.response import Response
from app01.ext.auth import QueryParamsAuthentication
from app01.ext.per import MyPermission1, MyPermission2, MyPermission3
from app01.ext.throttle import IPThrottle, UserThrottle
from app01 import models


# 这个匿名访问限流
class LoginView(APIView):
    authentication_classes = []
    permission_classes = []
    throttle_classes = [IPThrottle]

    def post(self, request):
        print(request.user, request.auth)
        # 1. 接受用户提交的用户名和密码
        print(request.data)  # body里面
        print(request.query_params)  # url拼接里面
        user = request.data.get("username", "")
        pwd = request.data.get("password", "")
        # 2. 数据库校验
        obj_user = models.UserInfo.objects.filter(username=user, password=pwd).first()
        if not obj_user:
            return Response({"status": False, "msg": "用户名或者密码错误"})

        # 3. 返回token
        token = str(uuid.uuid4())
        obj_user.token = token
        obj_user.save()
        return Response({"status": True, "data": token})


class UserView(APIView):

    def get(self, request):
        print(request.user, request.auth)
        return Response("UserView")


class OrderView(APIView):
    permission_classes = [MyPermission1, MyPermission2, MyPermission3]

    def get(self, request):
        print(request.user, request.auth)
        return Response({"status": True, "data": [1, 2, 3]})

    def check_permissions(self, request):
        no_permission_objects = []
        for permission in self.get_permissions():
            if permission.has_permission(request, self):
                return
            else:
                no_permission_objects.append(permission)
        else:
            self.permission_denied(
                request,
                message=getattr(no_permission_objects[0], 'message', None),
                code=getattr(no_permission_objects[0], 'code', None)
            )


# 用户登录限流
class AvatarView(APIView):
    throttle_classes = [UserThrottle, ]

    def get(self, request):
        print(request.user, request.auth)
        # return Response({"status": True, "data": [1, 2, 3]})
        return Response("AvatarView")
